package com.itheima.chapter10.producerconsumer22;

/*
三条线程通信
 */
public class Demo {
    public static void main(String[] args) {
        Printer1 p = new Printer1();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (Printer1.class) {
                        try {
                            p.print1();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (Printer1.class) {
                        try {
                            p.print2();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    synchronized (Printer1.class) {
                        try {
                            p.print3();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        }).start();

    }
}

class Printer {
    int flag = 1;

    public void print1() throws InterruptedException {
        while (flag != 1) {
            //等待
            Printer1.class.wait();
        }
        System.out.print("喜");
        System.out.print("欢");
        System.out.println("你");
        flag = 2;
        Printer1.class.notifyAll();
    }

    public void print2() throws InterruptedException {
        while (flag != 2) {
            //等待
            Printer1.class.wait();
        }
        System.out.print("新");
        System.out.print("的");
        System.out.print("心");
        System.out.println("跳");
        flag = 3;
        Printer1.class.notifyAll();
    }

    public void print3() throws InterruptedException {
        while (flag != 3) {
            //等待
            Printer1.class.wait();
        }
        System.out.print("夜");
        System.out.print("的");
        System.out.print("尽");
        System.out.println("头");
        flag = 1;
        Printer1.class.notifyAll();
    }
}